package com.csii.util;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;


import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: panChuanJiang
 * @create: 2021-07-08 11:07
 */
@Slf4j
public class CopyCodeUtil {
    @Test
    public void testCopyCode() {
        copyCode("D:\\temp\\src", "D:\\Java\\workspace\\keLan\\chengdu\\adhoc-pos\\csii-adhoc", "lqdtmnt", "LqdtMnt");
    }

    /**
     *
     * @param srcDir 生成代码的src文件夹路径
     * @param todir 本机项目csii-adhoc文件夹路径
     * @param moKuai 模块文件夹名称
     * @param prefix 表名转驼峰 例： cash_daily -》 CashDaily
     */
    private void copyCode(String srcDir, String todir, String moKuai, String prefix) {
        String javaDir = srcDir + File.separator + "main" + File.separator + "java";
        File dir = new File(javaDir);
        List<File> files = new ArrayList<>();
        getDirAllFile(dir, files);
        ceateToDir(todir,moKuai);
        files.forEach(x -> {
            if (x.getName().endsWith("Controller.java")) {
                String toFile = todir + File.separator + "csii-adhoc-web\\src\\main\\java\\com\\csii\\pos\\" + moKuai + File.separator + x.getName();
                nioCopyFile(x, toFile);
                List<String> imports = new ArrayList<>();
                imports.add("import com.csii.pos." + moKuai + ".service.I" + prefix + "Service;");
                imports.add("import com.csii.pos." + moKuai + ".vo." + prefix + "VO;");
                setPackageAndImport(new File(toFile), "package ", "package com.csii.pos." + moKuai + ";",imports);
            } else if (x.getName().endsWith("VO.java")) {
                String toFile = todir + File.separator + "csii-adhoc-dto\\src\\main\\java\\com\\csii\\pos\\" + moKuai + "\\vo" + File.separator + x.getName();
                nioCopyFile(x, toFile);
                setPackageAndImport(new File(toFile), "package ", "package com.csii.pos." + moKuai + ".vo;",null);
            } else if (x.getName().endsWith("Mapper.java")) {
                String toFile = todir + File.separator + "csii-adhoc-service\\src\\main\\java\\com\\csii\\pos\\" + moKuai + File.separator + "mapper\\" + x.getName();
                nioCopyFile(x, toFile);
                List<String> imports = new ArrayList<>();
                imports.add("import com.csii.pos."+moKuai+"."+prefix+";");
                setPackageAndImport(new File(toFile), "package ", "package com.csii.pos." + moKuai + ".mapper;",imports);
            } else if (x.getName().endsWith("Service.java")) {
                String toFile = todir + File.separator + "csii-adhoc-service\\src\\main\\java\\com\\csii\\pos\\" + moKuai + File.separator + "service\\" + x.getName();
                nioCopyFile(x, toFile);
                List<String> imports = new ArrayList<>();
                imports.add("import com.csii.pos."+moKuai+"."+prefix+";");
                setPackageAndImport(new File(toFile), "package ", "package com.csii.pos." + moKuai + ".service;",imports);
            } else if (x.getName().endsWith("ServiceImpl.java")) {
                String toFile = todir + File.separator + "csii-adhoc-service\\src\\main\\java\\com\\csii\\pos\\" + moKuai + File.separator + "service\\impl\\" + x.getName();
                nioCopyFile(x, toFile);
                List<String> imports = new ArrayList<>();
                imports.add("import com.csii.pos."+moKuai+"."+prefix+";");
                imports.add("import com.csii.pos."+moKuai+".mapper."+prefix+"Mapper;");
                imports.add("import com.csii.pos."+moKuai+".service.I"+prefix+"Service;");
                setPackageAndImport(new File(toFile), "package ", "package com.csii.pos." + moKuai + ".service.impl;",imports);
            } else if (x.getName().endsWith(".java")) {
                String toFile = todir + File.separator + "csii-adhoc-dto\\src\\main\\java\\com\\csii\\pos\\" + moKuai + File.separator + x.getName();
                nioCopyFile(x, toFile);
                setPackageAndImport(new File(toFile), "package ", "package com.csii.pos." + moKuai + ";",null);
            }
        });
    }

    private void ceateToDir(String todir, String moKuai) {
        File web = new File(todir + File.separator + "csii-adhoc-web\\src\\main\\java\\com\\csii\\pos\\" + moKuai);
        if (!web.exists()) web.mkdir();
        File mapper = new File(todir + File.separator + "csii-adhoc-service\\src\\main\\java\\com\\csii\\pos\\" + moKuai+"\\mapper");
        if (!mapper.exists()) mapper.mkdirs();
        File service = new File(todir + File.separator + "csii-adhoc-service\\src\\main\\java\\com\\csii\\pos\\" + moKuai+"\\service");
        if (!service.exists()) service.mkdirs();
        File serviceImpl = new File(todir + File.separator + "csii-adhoc-service\\src\\main\\java\\com\\csii\\pos\\" + moKuai+"\\service\\impl");
        if (!serviceImpl.exists()) serviceImpl.mkdir();
        File dto = new File(todir + File.separator + "csii-adhoc-dto\\src\\main\\java\\com\\csii\\pos\\" + moKuai);
        if (!dto.exists()) dto.mkdir();
        File vo = new File(todir + File.separator + "csii-adhoc-dto\\src\\main\\java\\com\\csii\\pos\\" + moKuai+"\\vo");
        if (!vo.exists()) vo.mkdir();
    }

    //@Test
    public void testNioCopyFile() {
        nioCopyFile(new File("D:\\tmp\\east.sql"), "D:\\tmp\\eastCopy.sql");
    }

    private void getDirAllFile(File dir, List<File> list) {
        File[] files = dir.listFiles();
        for (File f : files) {
            if (f.isFile()) {
                list.add(f);
            } else {
                getDirAllFile(f, list);
            }
        }
    }


    private void nioCopyFile(File fromFile, String target) {
        if (!fromFile.exists()) {
            log.error("源文件不存在");
            return;
        }
        File toFile = new File(target);
        try (FileInputStream in = new FileInputStream(fromFile);
             FileOutputStream out = new FileOutputStream(toFile)) {
            FileChannel channel = in.getChannel();

            int capacity = 1024;// 字节
            ByteBuffer bf = ByteBuffer.allocate(capacity);
            int length = -1;
            FileChannel outchannel = out.getChannel();
            while ((length = channel.read(bf)) != -1) {
                //将当前位置置为limit，然后设置当前位置为0，也就是从0到limit这块，都写入到同道中
                bf.flip();
                int outlength = 0;
                while ((outlength = outchannel.write(bf)) != 0) {
                }
                //将当前位置置为0，然后设置limit为容量，也就是从0到limit（容量）这块，
                //都可以利用，通道读取的数据存储到
                //0到limit这块
                bf.clear();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void setPackageAndImport(File fileText, String target, String src,List<String> imports) {//修改
        PrintWriter pw = null;
        StringBuffer buff = new StringBuffer();//临时容器!
        String line = System.getProperty("line.separator");//平台换行!
        try (BufferedReader br = new BufferedReader(new FileReader(fileText));) {
            for (String str = br.readLine(); str != null; str = br.readLine()) {
                if (str.contains(target)) {
                    str = src;
                    if (imports !=null && imports.size()!=0){
                        StringBuilder temp = new StringBuilder(str);
                        temp.append(line).append(line);
                        imports.forEach(x -> temp.append(x).append(line));
                        str = temp.toString();
                    }
                }
                buff.append(str).append(line);
            }
            pw = new PrintWriter(new FileWriter(fileText), true);
            pw.println(buff);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (pw != null)
                pw.close();
        }
    }
}
